package org.gw.building.repositories.dkgg;

import org.gw.building.model.Kqxx;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface KqxxRepository extends JpaRepository<Kqxx, String>{
	@Query( value = "select y.id, y.xhgh, y.xm, y.kc, k.dkbz, k.qiandao, k.qiantui from v_qmgc_ybmxx y left join t_qmgc_kqxx k on y.xhgh = k.xhgh WHERE y.kc=?1 and " +
			"(?2 is null or y.xhgh like ?2) and (?3 = 0 or (?3 = 1 and k.qiandao = 1) or (?3 = 10 and k.qiandao is null)) and " +
			"(?4 = 0 or (?4 = 1 and k.qiantui = 1) or (?4 = 10 and k.qiantui is null)) /*#pageable*/",
			countQuery = "SELECT count(1) from v_qmgc_ybmxx y left join t_qmgc_kqxx k on y.xhgh = k.xhgh WHERE y.kc=?1 and " +
					"(?2 is null or y.xhgh like ?2) and (?3 = 0 or (?3 = 1 and k.qiandao = 1) or (?3 = 10 and k.qiandao is null)) and " +
					"(?4 = 0 or (?4 = 1 and k.qiantui = 1) or (?4 = 10 and k.qiantui is null))",
			nativeQuery = true)
	Page<Kqxx> queryKqPage(String kc, String xhgh, String dao, String tui, Pageable psageable);

	@Query("from Kqxx k where k.kc = ?1 and (?2 is null or k.xhgh = ?2)")
	List<Kqxx> queryKqByKcAndXh(String kc, String xhgh);

	@Query( value = "select y.id, y.xhgh, y.xm, y.kc, k.dkbz, k.qiandao, k.qiantui " +
			"from v_qmgc_ybmxx y left join t_qmgc_kqxx k on y.xhgh = k.xhgh WHERE y.kc in ?1",
			nativeQuery = true)
	List<Kqxx> queryKqByKc(String[] kc);

	@Modifying
	@Query( value = "update t_qmgc_kqxx set dkbz=1 where qiandao = 1 and qiantui = 1 and kc = ?1 and (dkbz is null or dkbz = 3)",
			nativeQuery = true)
	void updateKaoqingZhengChang(String kc);

	@Modifying
	@Query( value = "update t_qmgc_kqxx set dkbz=3 where kc = ?1 and (dkbz is null or dkbz = 3) and (qiandao is null or qiandao = '' or qiantui is null or qiantui = '') ",
			nativeQuery = true)
	void updateKaoqingQueQing(String kc);

	@Modifying
	@Query( value = "update t_qmgc_kqxx set dkbz=2 where id = ?1",
			nativeQuery = true)
	void updateQingJiaInfo(String id);
}
